package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.entity.Myorder;
import com.chixing.mapper.MyorderMapper;
import com.chixing.service.IMyorderService;
import com.chixing.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author smith
 * @since 2025-05-21
 */
@Service
public class MyorderServiceImpl implements IMyorderService {
    //调用持久层
    @Autowired
    private MyorderMapper myorderMapper;

    @Override
    public Result getById(Integer myorderId) {
        Myorder myorder = myorderMapper.selectById(myorderId);
        if (myorder != null) {
            return Result.getSuccess(myorder);
        }
        return Result.getFail(null);
    }

    @Override
    public Result save(Myorder myorder) {
        // 生成订单号（格式：ORD+时间戳+随机数）
        String orderNumber = "ORD" + System.currentTimeMillis() +
                String.format("%04d", new Random().nextInt(10000));
        // insert into dish
        // rows 表示 Dish 表中受影响的行数, rows= 1 表示 添加了一条记录成功
        myorder.setOrderCreateTime(LocalDateTime.now());
        myorder.setCustId(1);
        myorder.setStatus("1");
        myorder.setOrderNumber(orderNumber);
        int rows = myorderMapper.insert(myorder);
        if (rows > 0) {
            return Result.getSuccess("添加订单成功");
        }
        return Result.getFail("添加订单失败");
    }

    @Override
    public Result getcustId(Integer custId) {
        QueryWrapper<Myorder> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("order_create_time");
        List<Myorder> myordersList = myorderMapper.selectList(wrapper);
        if (myordersList != null && myordersList.size() > 0)
            return Result.getSuccess(myordersList);
        return Result.getFail("优惠卷");
    }
}